﻿using System;
using System.Collections.Generic;
using System.Linq;
using Diploma.Models.IRepositories;

namespace Diploma.Models.Repositories
{
    internal class OrderDiplomRepository : IOrderDiplomRepository
    {
        private readonly DiplomaEntities dataContext;

        public OrderDiplomRepository(DiplomaEntities dataContext)
        {
            this.dataContext = dataContext;
        }

        public IEnumerable<OrderDiplom> GetAll()
        {
            return dataContext.OrderDiploms;
        }

        /// <summary>
        /// Получание приказа на diplom
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public OrderDiplom GetOrder(Guid id)
        {
            OrderDiplom model = dataContext.OrderDiploms.FirstOrDefault(r => r.Id == id);
            return model;
        }

        public OrderDiplom Create(OrderDiplom model)
        {
            dataContext.OrderDiploms.AddObject(model);
            SaveChanges();
            OrderDiplom newModel = dataContext.OrderDiploms.FirstOrDefault(r => r.Id == model.Id);
            return newModel;
        }

        public void AttachConsultant(Guid orderId, Guid consultantId)
        {
            var order = GetOrder(orderId);
            var consultant = DataManager.Instance.ConsultantOfPartRepository.Get(consultantId);
            if(order != null && consultant != null)
            {
                order.ConsultantOfParts.Add(consultant);
                dataContext.SaveChanges();
            }
        }

        public void DettachConsultant(Guid orderId, Guid consultantId)
        {
            var order = GetOrder(orderId);
            
            if (order != null)
            {
                var consultant = order.ConsultantOfParts.First(r => r.Id == consultantId);
                order.ConsultantOfParts.Remove(consultant);
                dataContext.SaveChanges();
            }
        }

        public void SaveChanges()
        {
            dataContext.SaveChanges();
        }
    }
}